﻿module Sustainalytics.ProductInvolvement {

    import Company = Sustainalytics.Company;
    import LRTM = Sustainalytics.LRTM;


    export class CompanyAssessmentDetailsController {

        //new paging logic
        public piAssessmentIndicators: PICompanyIndicatorDto[] = [];
        public pageSize: number = 3;
        public crtPage: number = 1;


        public piAssessmentDetails: PIAssessmentDetailsDto;
        public piIndicators : PIIndicatorDto[];

        public companyNameQueryString: string;
        public company: Company.CorporateDataExtendedDto;
        
        public notFoundMessage: string = '';
        public noClaims: boolean;
        public showIndicatorBubbles: boolean = false;

        //wether init is running
        public isInitLoading: boolean = true;

        private $routeParams: any;

        private userId: string;
        private accountId: string;
        //Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private RoutingService: Routing.IRoutingService,
            private CompanyService: Company.ICompanyService,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private CompanyAssessmentService: ICompanyAssessmentService,
            private PIPermissionsService: ProductInvolvement.Security.IPIPermissionsService,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService
            )
            {
                var ctx = this;
                ctx.$routeParams = ctx.RoutingService.getRouteParams();
                $scope['PICompanyDetailsCtrl'] = ctx;

                if (ctx.$rootScope['userInfo'] == null) {
                    ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
                }
                ctx.userId = ctx.$rootScope['userInfo'].userId;
                ctx.accountId = ctx.$rootScope['userInfo'].accountId;

                ctx.init();
            }

        private init(): ng.IPromise<any> {

            var ctx = this;
            ctx.isInitLoading = true;

            // get company name from route params
            var companyName: string = ctx.$routeParams['companyName'];
            ctx.companyNameQueryString = companyName;

            // get company by name
            var companyPromise = ctx.CompanyService.getByNameUrlFriendly(companyName);

            var def = ctx.$q.defer();

            //redirecting not needed anymore:  checking from within web api controller
            //ctx.hasCompanyPI = ctx.PIPermissionsService.hasCompanyPI();
            //if (!ctx.hasCompanyPI)
            //{
            //    // redirect to Overview tab
            //    this.$location.path('/research/' + ctx.companyNameQueryString);
            //    def.reject();
            //    return def.promise;
            //}


            // after obtaining the company info get also other related info
            companyPromise
                .success(function (company) {
                    ctx.company = company;

                    // get overall company summary
                    var piAssessmentDetailsPromise = ctx.loadPIAssessmentDetails(company.id);
                    var piIndicatorsPromise = ctx.loadPIIndicators();

                    ctx.$q.all([piAssessmentDetailsPromise, piIndicatorsPromise])
                        .then(function () {
                            def.resolve();
                        })
                        ['catch'](function () {
                            def.reject();
                        });
                })
                ['catch'](function () {
                    def.reject();
                });

            var promise = def.promise;

            promise['finally'](function () {
                ctx.isInitLoading = false;

                if (ctx.company != undefined) {
                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId,
                        'cookieDomain': 'none',
                        'name': 'globalAccess'
                    });

                    ga('globalAccess.set', 'dimension1', ctx.userId);

                    var dateNow = new Date();
                    var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
                    var gaObject: any = {
                        Date: dateNowString,
                        AccountId: ctx.accountId,
                        UserId: ctx.userId,
                        CompanyId: ctx.company.id
                    };

                    ga('globalAccess.send', {
                        'hitType': 'event',
                        'eventCategory': 'Research',
                        'eventAction': 'OnscreenComplianceReport',
                        'eventLabel': JSON.stringify(gaObject)
                    });
                }
            });

            return promise;
        }

        private loadPIAssessmentDetails(id: string): ng.IPromise<PIAssessmentDetailsDto>
        {
            var ctx = this;
            var getPromise: ng.IPromise<PIAssessmentDetailsDto> = ctx.CompanyAssessmentService.getCompanyAssessmentDetails(id);

            getPromise.then(
                (piAssessment: PIAssessmentDetailsDto) => {
                    ctx.piAssessmentDetails = piAssessment;
                    ctx.LoadMoreIndicators();
                    ctx.showIndicatorBubbles = true;
                },
                (reason) =>
                {
                    if (reason.status == 404) {

                        ctx.piAssessmentDetails = new PIAssessmentDetailsDto();
                        ctx.piAssessmentDetails.companyName = ctx.company.companyName;
                        ctx.piAssessmentDetails.country = ctx.company.country;
                        ctx.piAssessmentDetails.ticker = ctx.company.ticker;
                        ctx.piAssessmentDetails.companyNameSafeUrl = ctx.company.companyNameUrlFriendly;

                        if (reason.data.errCode !== null)
                        {
                            ctx.notFoundMessage = reason.data.message;
                        }
                    }
                    if (reason.status == 401)
                    {
                        ctx.noClaims = true;
                    }
                });

            return getPromise;
        }


        private loadPIIndicators(): ng.IPromise<PIIndicatorDto[]> {
            var ctx = this;
            var getPromise: ng.IPromise<PIIndicatorDto[]> = ctx.CompanyAssessmentService.getPIIndicators();
            getPromise.then((piIndicators: PIIndicatorDto[]) => {
                ctx.piIndicators = piIndicators;
            });
            return getPromise;
        }

        private hasNoClaimsOnAnyCompanyIndicator() : boolean
        {
            var ctx = this;
            var result = true;
            if (ctx.piAssessmentDetails != undefined && ctx.piAssessmentDetails != null) {
                ctx.piAssessmentDetails.indicators.forEach(function (element, index, array) {
                    result = result && !ctx.PIPermissionsService.hasValidPIIndicatorClaim('companyassessments', 'pi', element.symbol.toLowerCase());
                });
            }
            return result;
        }

        public DownloadPIReport() {
            var ctx = this;
            var taskNumber = LRTM.LongRunningTaskTypeEnum.PiReportPdf;

            //with dto
            //var data = new PIPdfExportTaskDto();
            //data.companyId = ctx.piAssessmentDetails.id;
            //data.companyName = ctx.piAssessmentDetails.companyName;
            var compName = ctx.piAssessmentDetails.companyName.replace('\\', '').replace(' ','').replace(',','-');

            var data = { companyId: ctx.piAssessmentDetails.id, companyName: compName };
            var promise = ctx.LongRunningTaskManagerService.runTask('ProductInvolvement_' + compName + '_' + moment().format("DD-MM-YYYY"), JSON.stringify(data), taskNumber, true, null);

            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            var dateNow = new Date();
            var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
            var gaObject: any = {
                Date: dateNowString,
                AccountId: ctx.accountId,
                UserId: ctx.userId,
                CompanyId: ctx.company.id
            };

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Research', 'eventAction': 'PDFComplianceReport', 'eventLabel': JSON.stringify(gaObject)
            });
        }

        public hasIndicatorClaim(indicator: string) {
            var ctx = this;
            return ctx.PIPermissionsService.hasValidPIIndicatorClaim('companyassessments', 'pi', indicator.toLowerCase())
        }

        public GetPDFDownloadEnabled() : boolean {
            var ctx = this;
            var result = true;

            if ((ctx.notFoundMessage != undefined && ctx.notFoundMessage.length > 0) || (ctx.noClaims != undefined && ctx.noClaims === true))
            {
                result = false;
            }

            return result;
        }

        public GetShowMoreEnabled(): boolean {

            var ctx = this;

            if (ctx.piAssessmentDetails == undefined ||
                ctx.piAssessmentDetails.indicators == undefined ||
                ctx.piAssessmentDetails.indicators.length === 0 ||
                ctx.piAssessmentIndicators.length === 0 ||
                ctx.piAssessmentDetails.indicators.length === ctx.piAssessmentIndicators.length)
            {
                return false;
            }
            
            return true;
        }

        public GetShowMoreVisible(): boolean {
            var ctx = this;

            if (ctx.piAssessmentDetails.indicators == undefined ||
                ctx.piAssessmentDetails.indicators.length === 0 ||
                ctx.piAssessmentIndicators.length === 0)
            {
                return false;
            }

            return true;
        }

        public LoadMoreIndicators() : any
        {
            var ctx = this;
            var pageItems = ctx.piAssessmentDetails.indicators.slice((ctx.crtPage - 1) * ctx.pageSize, ctx.crtPage * ctx.pageSize);

            pageItems.forEach((item) => {
                ctx.piAssessmentIndicators.push(item);
            });

            ctx.crtPage++;
        }

        public GetIndicatorIconState(indicator: string) {

            var ctx = this;

            var result = "off";

            if (ctx.piAssessmentDetails != undefined
                && ctx.piAssessmentDetails != null
                && ctx.piAssessmentDetails.indicators != undefined
                && ctx.piAssessmentDetails.indicators != null)
            {
                $.each(ctx.piAssessmentDetails.indicators, function (index, element: PICompanyIndicatorDto)
                {
                    if (element.symbol == indicator && ctx.PIPermissionsService.hasValidPIIndicatorClaim('companyassessments', 'pi', element.symbol.toLowerCase()))
                    {
                        result = "on";
                        return false;
                    }
                });
            }

            return result;
        }
    }


    // register controller 
    angular.module('Sustainalytics.ProductInvolvement').controller('CompanyAssessmentDetailsController',
        ['$rootScope', '$scope', 'RoutingService', 'CompanyService', '$q', '$location', 'CompanyAssessmentService',
            'PIPermissionsService', 'LongRunningTaskManagerService', CompanyAssessmentDetailsController]);
}
